using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;

public class CharacterController : MonoBehaviour
{
    private PlayerInput _playerInput; 
    [SerializeField] private Vector2 _moveDir;
    [SerializeField] private float moveSpeed = 5f;
    public Transform _camera;
    public Transform _model;
    [SerializeField] private float RotateSpeed = 10f;
    private Rigidbody _rb;

    [Header("Cinemachine Cams")]
    public Cinemachine.CinemachineFreeLook thirdPersonCam;

    public GameObject third;
    public Cinemachine.CinemachineVirtualCamera firstPersonCam;
    public GameObject first;
    private bool isFirstPerson;

    private void Awake()
    {
        _rb = GetComponent<Rigidbody>();
        _playerInput = new PlayerInput();

        _playerInput.GamePlay.Move.performed += ctx => _moveDir = ctx.ReadValue<Vector2>();
        _playerInput.GamePlay.Move.canceled += ctx => _moveDir = Vector2.zero;

        // 绑定切换视角按键
        _playerInput.GamePlay.SwitchView.performed += _ => ToggleView();
    }

    private void ToggleView()
    {
        isFirstPerson = !isFirstPerson;
        if (isFirstPerson)
        {
            third.SetActive(false);
            first.SetActive(true);
            firstPersonCam.Priority = 20;
            thirdPersonCam.Priority = 10;
        }
        else
        {
            third.SetActive(true);
            first.SetActive(false);
            firstPersonCam.Priority = 10;
            thirdPersonCam.Priority = 20;
        }
    }

    private void OnEnable() => _playerInput.Enable();
    private void OnDisable() => _playerInput.Disable();

    private void FixedUpdate()
    {
        // 决定使用哪个摄像机方向
        Transform cam = isFirstPerson ? firstPersonCam.transform : thirdPersonCam.transform;
        Vector3 camForward = cam.forward;
        Vector3 camRight = cam.right;
        camForward.y = 0;
        camRight.y = 0;
        camForward.Normalize();
        camRight.Normalize();

        Vector3 moveWorld = camForward * _moveDir.y + camRight * _moveDir.x;
        _rb.velocity = moveWorld * moveSpeed;

        if (!isFirstPerson && moveWorld.sqrMagnitude > 0.01f)
        {
            Quaternion targetRot = Quaternion.LookRotation(moveWorld);
            _model.rotation = Quaternion.Slerp(_model.rotation, targetRot, Time.deltaTime * RotateSpeed);
        }
    }
}

